<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style type="text/css">
      * {
        margin: 0;
        padding: 0;
      }
      .contiar {
        width: 100vw;
        height: 100vh;
        background: url(./bg-16c5dcec.png);
        background-size: cover;
        border: solid;
      }
      .box {
        position: fixed;
        width: 1920px;
        border: 1px solid red;
        height: 1080px;
        background-color: rebeccapurple;
        /* 盒子缩放的基点 */
        transform-origin: left top;
        left: 50%;
        top: 50%;
      }
      .top,
      .bottom {
        width: 100px;
        height: 100px;
        margin-top: 100px;
        margin-left: 50px;
      }
      .top {
        background-color: aqua;
      }
      .bottom {
        background-color: hotpink;
      }
    </style>
  </head>
  <body>
    <div class="contiar">
      <div class="box">
        <div class="top"></div>
        <div class="bottom"></div>
      </div>
    </div>
    <script>
      //一上来先触发一遍
      let box = document.querySelector('.box')
      //translate(-50%, -50%)加在这里是因为在js中添加transform时候会把原来的动画覆盖掉
      box.style.transform = `scale(${getScale()}) translate(-50%, -50%)`
      function getScale(w = 1920, h = 1080) {
        const ww = window.innerWidth / w
        const hh = window.innerHeight / h
        box.children[0].innerHTML = 'ww' + ww
        box.children[1].innerHTML = 'hh' + hh
        return ww > hh ? hh : ww
        //必须根据最小的值进行缩放不然就达不到想要的效果
        //hh小于ww呢只能视口高度小于原始高度，视口宽度大于等于原始宽度的时候相反也是一样的，所以只能根据最小的数据进行缩放
      }
      //当视口尺寸变化时触发
      window.onresize = () => {
        box.style.transform = `scale(${getScale()}) translate(-50%, -50%)`
      }
    </script>
  </body>
</html>
